package com.ouroboroswiki.core.content.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.ouroboroswiki.core.AbstractProxiedContent;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentUtil;

public class EscapeXMLContentProxy extends AbstractProxiedContent {
	
	private static final Logger log = Logger.getLogger(EscapeXMLContentProxy.class.getName());
	
	private String mimeType;
	
	public EscapeXMLContentProxy( Content proxied ) {
		super( proxied );
	}
	
	@Override
	public String getMimeType() {
		return mimeType;
	}

	public void setMimeType(String mimeType) {
		this.mimeType = mimeType;
	}

	@Override
	public void write(OutputStream outs) throws IOException, ContentException {
		InputStream ins = ContentUtil.openInputStream(this.proxied);
		Writer writer = new OutputStreamWriter( outs );
		try {
			InputStreamReader reader = new InputStreamReader( ins );
			int c;
			while( ( c = reader.read() ) >= 0 ) {
				switch( c ) {
				case '>':
					writer.write("&gt;");
					break;
				case '<':
					writer.write("&lt;");
					break;
				case '&':
					writer.write("&amp;");
					break;
				case '\"':
					writer.write("&quot;");
					break;					
				default:
					writer.write(c);
				}
			}
			writer.flush();
		} finally {
			try {
				ins.close();
			} catch( IOException ex ) {
				log.log( Level.WARNING, "couldn't close "+proxied.getUniqueName()+" in "+proxied.getRepositoryName(), ex );
			}
		}
	}
}
